<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.successStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="status in successStatus"
            :key="status.value"
            :label="status.label"
            :value="status.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送时间" prop="sendTime">
        <el-date-picker clearable
                        size="small"
                        style="width: 240px"
                        v-model="dateRangeSendTime"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="租户" prop="tenantId">
        <el-select v-model="queryParams.tenantId" filterable clearable size="small" placeholder="请选择租户"
                   style="width: 100%" @keyup.enter.native="handleQuery">
          <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.tenantId+'/'+item.tenantName" :value="item.tenantId"/>
        </el-select>
      </el-form-item>
      <el-form-item class="search">
        <hide-search :show-search.sync="showSearch"></hide-search>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-content">
<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sms:smsRecord:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="smsRecordList" @selection-change="handleSelectionChange">
      <el-table-column label="配置ID" align="center" prop="configId"/>
      <el-table-column label="手机号" align="center" prop="phoneNumber"/>
      <el-table-column label="状态" align="center" prop="successStatus" :formatter="statusFormat"/>
      <el-table-column label="短信内容" align="center" prop="content" width="300"/>
      <el-table-column label="发送时间" align="center" prop="sendTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" align="center" prop="failReason" show-overflow-tooltip/>
      <el-table-column label="返回结果" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="租户" align="center" prop="tenantId" :formatter="formatTenant"/>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template v-slot="scope">-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      </div>

    <!-- 添加或修改短信发送记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="配置ID" prop="configId">
          <el-input v-model="form.configId" placeholder="请输入配置id"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="短信内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-date-picker clearable
                          v-model="form.sendTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择发送时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="租户编码" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户编码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listSmsRecord, getSmsRecord, delSmsRecord, addSmsRecord, updateSmsRecord} from "@/api/sms/smsRecord";
  import {listTenant} from "@/api/system/tenant"

  export default {
    name: "SmsRecord",
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total: 0,
        dateRangeSendTime: [],
        tenantList: [],
        tenantFormat: [],
        // 短信发送记录表格数据
        smsRecordList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        successStatus: [
          {label: "成功", value: "1"},
          {label: "失败", value: "0"}
        ],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          configId: undefined,
          phoneNumber: undefined,
          successStatus: undefined,
          content: undefined,
          sendTime: undefined,
          tenantId: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          id: [
            {required: true, message: "主建不能为空", trigger: "blur"}
          ],
          configId: [
            {required: true, message: "配置id不能为空", trigger: "blur"}
          ],
          phoneNumber: [
            {required: true, message: "手机号不能为空", trigger: "blur"}
          ],
          successStatus: [
            {required: true, message: "0-失败 1-成功不能为空", trigger: "blur"}
          ],
          content: [
            {required: true, message: "短信内容不能为空", trigger: "blur"}
          ],
          sendTime: [
            {required: true, message: "短信发送时间不能为空", trigger: "blur"}
          ],
          remark: [
            {required: true, message: "备注不能为空", trigger: "blur"}
          ],
          tenantId: [
            {required: true, message: "租户编码不能为空", trigger: "blur"}
          ]
        }
      };
    },
    created() {
      listTenant({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.tenantList = response.rows;
        if (this.tenantList) {
          for (let item of this.tenantList) {
            this.tenantFormat[item.tenantId] = item.tenantName;
          }
        }
        this.getList();
      });
    },
    methods: {
      /** 查询短信发送记录列表 */
      getList() {
        this.loading = true;
        if (null != this.dateRangeSendTime && '' != this.dateRangeSendTime) {
          this.queryParams.params['beginCreateTime'] = this.dateRangeSendTime[0]
          this.queryParams.params['endCreateTime'] = this.dateRangeSendTime[1]
        }
        listSmsRecord(this.queryParams).then(response => {
          this.smsRecordList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      formatTenant(row, column) {
        let show = "";
        if (row.tenantId) {
          show = this.tenantFormat[row.tenantId];
        }
        return show;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          configId: undefined,
          phoneNumber: undefined,
          successStatus: "0",
          content: undefined,
          sendTime: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined,
          tenantId: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRangeSendTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加短信发送记录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const id = row.id || this.ids
        getSmsRecord(id).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改短信发送记录";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateSmsRecord(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addSmsRecord(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(() => {
          this.loading = true;
          return delSmsRecord(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('sms/smsRecord/export', {
          ...this.queryParams
        }, `smsRecord_${new Date().getTime()}.xlsx`)
      },
      statusFormat(row, column) {
        let show = this.successStatus
          .filter(status => status.value === row.successStatus)
          .map(status => status.label)
        return show === [] ? '' : show[0]
      }
    }
  };
</script>
